package com.demo.project_template.filter;

import com.alibaba.fastjson2.JSON;
import com.demo.project_template.constant.AuthenticationConstants;
import com.demo.project_template.entity.LoginUser;
import com.demo.project_template.util.JwtUtil;
import com.demo.project_template.util.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author yyl25
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.fillInStackTrace();
            throw new RuntimeException("token非法");
        }
        String type = request.getHeader("type");
        if (String.valueOf(0).equals(type)){
            //从redis中获取用户信息
            LoginUser loginUser = JSON.parseObject(redisUtil.get(AuthenticationConstants.BACKSTAGE_USER_LOGIN_TOKEN+ userid), LoginUser.class);
            if(Objects.isNull(loginUser)){
                throw new RuntimeException("用户未登录");
            }
            //存入SecurityContextHolder
            //获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }else if (String.valueOf(1).equals(type)){
            //从redis中获取用户信息
            String userToken = redisUtil.get(AuthenticationConstants.USER_LOGIN_TOKEN+ userid);
            if(Objects.isNull(userToken)){
                throw new RuntimeException("用户未登录");
            }
            System.out.println("token:"+token);
            System.out.println("userToken:"+userToken);
            if (Objects.equals(token,userToken)){
                throw new RuntimeException("token异常");
            }
            //存入SecurityContextHolder
            //获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userid,null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }else {
            throw new RuntimeException("请求异常");
        }
        //放行
        filterChain.doFilter(request, response);
    }
}

